//电影管理

var express = require('express');
var router = express.Router();
var sqlQuery = require('../../../module/sql');
var fs = require('fs')
//引入上传模块
var multer = require('multer');
//上传的配置
var upload = multer({dest:"./public/upload"});


/* GET users listing. */
router.get('/', async(req, res, next)=> {
  let fid = req.query.id
  let sqlStr = 'select * from film where id = ?';
  let result = await sqlQuery(sqlStr,[fid])
  let film =  result[0]
  let type = await getType()
  let options = {film,type}
  res.render('admin/film/filmedit',options)
  
});


//获取电影类型
async function getType(){
  let sqlStr1 = 'select * from type'
  let result1 = await sqlQuery(sqlStr1);
  //结果返回
  return Array.from(result1);
}


router.post('/poster',upload.single('poster'), async(req, res, next)=> {
  let filmid = req.body.filmid
  let result = rename(req)
  res.json(result)
})
//改名函数
function rename(req) {
  //重命名操作
  let oldPath = req.file.destination+"/"+req.file.filename;
  let newPath = req.file.destination+"/"+req.file.filename+req.file.originalname;
  fs.rename(oldPath,newPath,()=>{
    //console.log("重命名成功")
  })
  return {
    state:'ok',
    imgUrl:"/upload/"+req.file.filename+req.file.originalname
  }
 }


router.post('/', async(req, res)=>{
  let filmName = req.body.filmName
  let Typeid = req.body.typeid
  let year = req.body.year
  let director = req.body.director
  let region = req.body.region
  let brief = req.body.brief
  let movieUrl = req.body.movieUrl
  let poster = req.body.img_h
  let fid = req.body.fid
  let sqlStr3 = "update film set filmName=?, Typeid=?, year=?, director=?, region=?, brief=?, movieUrl=?, poster=? where id = ?"
  let arr = [filmName,Typeid,year,director,region,brief,movieUrl,poster,fid]
  await sqlQuery(sqlStr3,arr)
  res.json({
    state:"ok",
    content:"电影信息更新成功"
  })

})


module.exports = router;
